//https://leetcode.cn/problems/binary-tree-inorder-traversal/
package codeRandomThoughts.Test94二叉树的中序遍历;

import codeRandomThoughts.utils.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        inorder(root, list);
        return list;

    }

    public void inorder(TreeNode root, List<Integer> list) {
        //递归停止条件
        if (root == null) {
            return;
        }

        inorder(root.left, list);
        list.add(root.val);
        inorder(root.right, list);
    }

    /**
     * 中序遍历的迭代写法
     *
     * @param root
     * @return
     */
    public List<Integer> inorderTraversal2(TreeNode root) {
        List<Integer> list = new ArrayList<>();

        Stack<TreeNode> stack = new Stack<>();
        TreeNode pt = root;

        while (pt != null || !stack.isEmpty()) {
            if (pt != null) {
                stack.push(pt);
                pt = pt.left;
            } else {
                TreeNode node = stack.pop();
                list.add(node.val);
                pt = node.right;
            }
        }
        return list;
    }

}
